<template>
  <view class="container">
    <view class="header">
      <image class="logo" src="/static/images/e9logo2.png" mode="widthFix" />
      <view class="title">E9交付小程序</view>
      <view class="desc">欢迎登录进行使用！</view>
    </view>

    <view class="login-form">
      <!-- 手机号快捷登录 -->
      <template v-if="usePhoneLogin">
        <view class="btn-group">
          <button
            class="TimUi-btn block bgc-52D9"
            @getphonenumber="handleGetPhoneNumber"
            open-type="getPhoneNumber"
          >
            手机号快速验证
          </button>
          <button
            @click="usePhoneLogin = false"
            class="TimUi-btn block"
            text="账号登录"
          >
            账号登录
          </button>
        </view>
      </template>
      <template v-else>
        <u--form
          labelPosition="left"
          :model="formModel"
          :rules="rules"
          ref="uForm"
        >
          <view class="login-form-item">
            <u-form-item label="账号" prop="identifier">
              <u--input
                v-model="formModel.identifier"
                placeholder="请输入账号"
                border="none"
                :customStyle="{
                  padding: 0
                }"
              ></u--input>
            </u-form-item>
          </view>
          <view class="login-form-item">
            <u-form-item label="密码" prop="credential">
              <u--input
                v-model="formModel.credential"
                type="password"
                placeholder="请输入密码"
                border="none"
                :customStyle="{
                  padding: 0
                }"
              ></u--input>
            </u-form-item>
          </view>
        </u--form>
        <view class="btn-group">
          <button class="TimUi-btn block bgc-52D9" @click="handleLogin">
            登录
          </button>
          <button class="TimUi-btn block" @click="cancelPasswordLogin">
            返回
          </button>
        </view>
      </template>
    </view>

    <view class="authorization" v-if="!usePhoneLogin">
      <u-checkbox-group
        v-model="checkList"
        placement="column"
        @change="checkboxChange"
      >
        <u-checkbox
          shape="circle"
          label="阅读并同意"
          name="1"
          labelColor="#1D2128"
          labelSize="32rpx"
        ></u-checkbox>
      </u-checkbox-group>
      <text class="link"> 《协议条款》 </text>
      <text class="link"> 和 </text>
      <text class="link"> 《隐私政策》 </text>
    </view>
  </view>
</template>

<script>
import { loginApi, phoneLoginApi } from '@/api/user'
const generateFormModel = () => ({
  identifier: 'admin',
  credential: '123456',
  imei: uni.getStorageSync('deviceId') || null
})

export default {
  data() {
    return {
      usePhoneLogin: true,
      formModel: generateFormModel(),
      rules: {
        identifier: {
          type: 'string',
          required: true,
          message: '请输入手机号/邮箱',
          trigger: ['blur', 'change']
        },
        credential: {
          type: 'string',
          required: true,
          message: '请输入密码',
          trigger: ['blur', 'change']
        }
      },
      checkList: [],
      isOverdue: false // 设备id变更需要用账号密码重新登录
    }
  },
  methods: {
    checkboxChange(val) {
      this.checkList = val
    },
    handleLogin() {
      const thisObj = this
      if (this.checkList.length === 0) {
        this.$u.toast('请先阅读并同意协议')
      } else {
        this.$refs.uForm
          .validate()
          .then(async (res) => {
            if (thisObj.isOverdue || thisObj.formModel.imei === null)
              this.getDeviceId()
            this.loginFn(this.formModel, 'account')
          })
          .catch((errors) => {
            uni.$u.toast('校验失败')
          })
      }
    },
    // 手机号登录
    async handleGetPhoneNumber(e) {
      //   if (!this.isAgree) {
      //     this.$u.toast('请先阅读并同意协议')
      //     return
      //   }
      if (e.detail.errMsg !== 'getPhoneNumber:ok') {
        // this.loading = false
        return
      }
      const { code, encryptedData, iv } = e.detail
      if (!this.formModel.imei) this.getDeviceId()
      const parmas = {
        code,
        imei: this.formModel.imei
      }
      this.loginFn(parmas, 'phone')
    },
    loginFn(data, type) {
      const $api = type === 'account' ? loginApi : phoneLoginApi
      $api(data).then(async (res) => {
        console.log(res)

        const { token, accountId } = res
        uni.setStorageSync('Token', token)
        uni.setStorageSync('accountId', accountId)
        let platformInfos = []
        if (res.platformInfos && res.platformInfos.length > 0) {
          platformInfos = res.platformInfos.filter(
            (item) => item.appDomain && item.appDomain !== ''
          )
        }
        uni.setStorageSync('SET_PLATFORMINFOS', JSON.stringify(platformInfos))
        uni.navigateTo({
          url: '/pages/project/list'
        })
      })
    },
    // 获取设备id
    getDeviceId() {
      let info = uni.getSystemInfoSync()
      this.formModel.imei = info.deviceId
      uni.setStorageSync('deviceId', info.deviceId)
    },
    // 取消密码登录
    cancelPasswordLogin() {
      this.usePhoneLogin = true
      this.formModel = generateFormModel()
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  &::after {
    content: '';
    z-index: -1;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 40%;
    background: url(/static/images/login.png) no-repeat;
    background-size: 100% 100%;
  }

  .header {
    display: grid;
    grid-template-columns: auto 1fr;
    grid-template-rows: auto auto;
    gap: 4rpx 10rpx;
    align-items: center;
    width: fit-content;
    margin: 30% 32rpx 0;
    color: #fff;

    .logo {
      grid-column: 1;
      width: 50rpx;
      height: 43rpx;
      //   width: 120rpx;
      //   height: 104rpx;
    }

    .title {
      grid-column: 2;
      text-align: left;
      font-size: 32rpx;
      font-weight: 600;
      letter-spacing: 0.2em;
    }

    .desc {
      grid-column: 1 / span 2;
      grid-row: 2;
      font-size: 28rpx;
      letter-spacing: 0.2em;
    }
  }

  .login-form {
    margin: 40% 32rpx 0;

    .login-form-item {
      margin: 0 0 32rpx;
      padding: 8rpx 16rpx;
      border-bottom: 2rpx solid #ddd;
      border-radius: 0;

      .u-form-item {
        background-color: red;
      }
    }

    .btn-group {
      margin: 120rpx 0 0;

      .TimUi-btn {
        margin: 20rpx 0 0;

        &:active {
          color: white;
        }
      }
    }
  }

  .authorization {
    display: flex;
    justify-content: center;
    align-items: center;
    position: fixed;
    bottom: calc(64rpx - env(safe-area-inset-bottom));
    left: 0;
    right: 0;
    padding-bottom: env(safe-area-inset-bottom);
    font-size: 32rpx;

    .link {
      color: #0052d9;
    }
  }
}
</style>
